import { Injectable } from '@angular/core';

import notify from 'devextreme/ui/notify';

import { HttpInterceptorService } from "../http-utils.service";

/**
 * interface TreeData
 * 组织机构树接口定义
 */ 
export interface TreeItem {
  expanded: boolean;
  id: number;
  items?: Array<TreeItem>
  parentId: null|number;
  text: string;
};
// 组织机构树集合接口定义
export type TreeItems = Array<TreeItem>;


@Injectable()
export class PurTreeService {

  constructor(
    public httpser: HttpInterceptorService
  ) { }
  /**
   * 获取组织机构树
   * @param orgInfo 可能是 orgId 或者 orgName 异步获取树节点数据和模糊查询共用
   * @param key 'orgName' | 'orgId'
   * @returns {Promise<TreeItems>}
   */
  queryOrgList(orgInfo: number | string, key: string, url: String): Promise<TreeItems> {
    return this.httpser.request({
      method: 'post',
      url,
      data: {[key]:orgInfo}
    }).then(res => this.validOrgTree(res));
  }
  validOrgTree(res): TreeItems{
    const reslut = new Array<TreeItem>();
    const valIsArray = res.resultValue instanceof Array;
    if((res.success || res.success === 'true') && valIsArray){
      return res.resultValue;
    };
    return reslut;
  }

  getTreeData(url: string, params: object = {}): Promise<TreeItems> {
    return this.httpser.request({
      method: 'post',
      url,
      data: params
    }).then(res => this.validOrgTree(res));
  }
  // ---
  /**
   * 弹出通知失败窗口
   * @param msg
   */
  notifyFailMsg(msg){
    if (Object.is(msg, undefined) || Object.is(msg, '')
      || Object.is(msg, null)) {
      msg = '系统出现异常！';
    }
    notify({
      message: msg,
      position: {
        my: "center top",
        at: "center top"
      }
    }, "error", 1500);
  }
}
